/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hiof.voiceguide;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.widget.Toast;
import com.hiof.Configuration;
import com.hiof.R;
import com.hiof.utility.Utility;

import java.util.Locale;

/**
 * @author manish
 */
public class TextToSpeechPlayer implements Speakable, TextToSpeech.OnInitListener {

    private TextToSpeech tts;
    private String message;
    private static TextToSpeechPlayer instance;
    private static final int MY_DATA_CHECK_CODE = 1;

    private TextToSpeechPlayer() {
    }

    public static TextToSpeechPlayer getInstance() {
        if (instance == null) {
            instance = new TextToSpeechPlayer();
        }
        return instance;
    }

    public void destroy() {
        if (tts != null) {
            tts.shutdown();
            tts = null;
        }
    }

    public void init(Context context) {
        tts = new TextToSpeech(context, this);
    }

    public void setArtifact(int artifactId) {
        this.message = Configuration.getInstance().getCurrentContext().getString(artifactId);
    }

    public void setArtifact(String message) {
        this.message = message;
    }

    @Override
    public void stop() {
        if (null != tts) {
            tts.stop();
        }
    }

    @Override
    public void speak() {
        if(tts != null)
            tts.speak(message, TextToSpeech.QUEUE_FLUSH, null);
    }

//    private void checkTextToSpeechInstalled() {
//        Intent checkIntent = new Intent();
//        checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
//        startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
//    }

    @Override
    public void onInit(int status) {
        Toast.makeText(Configuration.getInstance().getCurrentContext(), "TTS started", Toast.LENGTH_SHORT).show();
        // status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
        if (status == TextToSpeech.SUCCESS) {
            // Set preferred language to US english.
            // Note that a language may not be available, and the result will indicate this.
            int result = tts.setLanguage(Locale.UK);
            // Try this someday for some interesting results.
            // int result mTts.setLanguage(Locale.FRANCE);
            if (result == TextToSpeech.LANG_MISSING_DATA ||
                    result == TextToSpeech.LANG_NOT_SUPPORTED) {

            } else {

            }
        } else {
            // Initialization failed.
            Utility.error(this.getClass().toString(), "Could not initialize TextToSpeech.");
        }
    }
}
